package com.cxb.utils;

import android.content.Context;
import android.speech.tts.TextToSpeech;
import android.util.Log;

import java.util.Locale;

/**
 * Author jerry
 * date: 2016/5/31.
 */
public class TTSUtil {
	private static TextToSpeech mTTS;
	public static void init(Context context){
		if(mTTS == null){
			TextToSpeech.OnInitListener initListener = new TextToSpeech.OnInitListener() {
				@Override
				public void onInit(int status) {
					if (status == TextToSpeech.SUCCESS) {
						int code = mTTS.setLanguage(Locale.CHINA);
						if (code != TextToSpeech.LANG_AVAILABLE && code != TextToSpeech.LANG_COUNTRY_AVAILABLE) {
							Log.e("TTSUtil", "TTS: unsupport language");
						}
					}
				}
			};
			mTTS = new TextToSpeech(context, initListener);
		}

	}

	public static int playText(String content) {
		if (mTTS == null) {
			return TextToSpeech.ERROR;
		}
		return mTTS.speak(content, TextToSpeech.QUEUE_ADD, null);
	}

	public static void release() {
		if (mTTS == null) {
			return;
		}
		if (mTTS.isSpeaking()) {
			mTTS.stop();
		}
		mTTS.shutdown();
		mTTS = null;
	}
}
